﻿using System.IO;
using System.Data;
using System.Diagnostics.Contracts;
using System;
using Common.Logging;

namespace BusStopDataAccess
{
    /// <summary>
    /// A helper class to access the database without having to manage the database connection
    /// </summary>
    public static class ScheduleInfoFactory
    {
        private static readonly ILog log = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// Returns a disposable reference to the database
        /// </summary>
        /// <param name="file">The SQLite database file</param>
        /// <returns>A disposable reference to the database</returns>
        public static DisposeableScheduleInfo OpenDatabaseFile(FileInfo file)
        {
            Contract.Requires(file != null);
            Contract.Requires(file.Exists);

            System.Data.SQLite.SQLiteConnection dbconn = null;
            ScheduleInfo si = null;
            try
            {
                dbconn = new System.Data.SQLite.SQLiteConnection("data source=\"" + file.FullName.Replace("\\", "\\\\") + "\"");
                dbconn.Open();
                si = new ScheduleInfo(dbconn);
                return new DisposeableScheduleInfo(dbconn, si);
            }
            catch (Exception e)
            {
                log.Error("Couldn't open database file: " + file, e);
                try
                {
                    if (si != null)
                    { si.Dispose(); }
                }
                catch { }
                try
                {
                    if (dbconn != null)
                    { dbconn.Dispose(); }
                }
                catch { }
                return null;
            }
        }        
    }
}
